import React from "react";
import { connect } from "react-redux";
import fetch from "../../utils/fetch";
import { Input, Button, Row, Col, Icon, Select, Modal, DatePicker, message } from "antd";
import UserTable from "./UserTable";
import UserModal from "./UserModal";
import { cloneDeep } from "lodash";
import "./index.scss";
import { fetchUsers } from '../../actions/appData';

const dateFormat = "YYYY-MM-DD";

class UserManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showQuickJumper: true
      },
      selectedRowKeys: [],
      showUserModal: false,
      selectUser: {},
      action: "add",
      filterData: {
        _id: "",
        tel: "",
        nickname: "",
        frozenTo: "0"
      },
      showFreezModal: false,
      freezDate: null,
      selectUserId: '',
    };
  }
  componentDidMount() {
    const { pagination } = this.state;
    const { current, pageSize } = pagination;
    this.getUserService(current, pageSize );
  }

  getUserService = (current, pageSize, query = {}) => {
    fetch("/api/getUsers", {
      current,
      pageSize,
      ...query
    }).then(data => {
      const { pagination } = this.state;
      pagination.total = data.total;
      pagination.current = current;
      this.setState({ list: data.list, pagination });
    });
  };

  handleOk = () => {
    this.setState({ showUserModal: false });
  };
  handleCancel = () => {
    this.setState({ showUserModal: false });
  };

  removeUser = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys: userIds } = this.state;
    fetch("/api/removeUsers", { userIds }).then(() => {
      // dispatch(fetchUsers());
      this.onSearch();
      this.setState({ selectedRowKeys: [] });
    });
  };

  authUser = (_id, isAuth) => {
    fetch("/api/updateUser", { _id, isAuth }).then(() => {
      this.onSearch();
    });
  };

  freezUser = (_id, flag) => {
    if (!flag) {
      fetch("/api/updateUser", { _id, frozenTo: 0 }).then(() => {
        this.setState({showFreezModal: false});
        this.onSearch();
      });
    } else {
      this.setState({showFreezModal: true, freezDate: null, selectUserId: _id});
    }
  };

  onFreezSave  = () => {
    const { selectUserId, freezDate } = this.state;
    if (!freezDate) {
      message.warning('请选择到期日');
      return;
    }
    fetch("/api/updateUser", { _id: selectUserId, frozenTo: freezDate.unix() }).then(() => {
      this.setState({showFreezModal: false});
      this.onSearch();
    });
  };


  onFilterChange = (value, key) => {
    const { filterData } = this.state;
    filterData[key] = value;
    this.setState({ filterData });
  };

  onSearch = () => {
    const filterData = cloneDeep(this.state.filterData);
    const { _id, tel, nickname, frozenTo } = filterData;
    if (!_id) {
      delete filterData._id;
    }
    if (!tel) {
      delete filterData.tel;
    }
    if (!nickname) {
      delete filterData.nickname;
    }
    if (frozenTo === '0') {
      delete filterData.frozenTo;
    } else if (frozenTo === '1') {
      filterData.frozenTo = {$in: [0, undefined]}
    } else {
      filterData.frozenTo = {$gt: 0}
    }
    this.getUserService(1, 10, filterData);
  };

  handleCancel = () => {
    this.setState({ showUserModal: false });
    this.onSearch();
  };

  editUser = (user, action) => {
    this.setState({
      showUserModal: true,
      selectUser: user,
      action
    });
  };

  onRowSelect = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  resetFilter = () => {
    this.setState(
      {
        filterData: {
          _id: "",
          tel: "",
          nickname: "",
          frozenTo: "0"
        }
      },
      this.onSearch
    );
  };

  render() {
    const {
      list,
      pagination,
      selectedRowKeys,
      showUserModal,
      selectUser,
      action,
      filterData,
      showFreezModal,
      freezDate
    } = this.state;

    return (
      <div className="user-manage-wrapper">
        <Row gutter={16} className="search-bar">
          <Col span={4}>
            <Input
              value={filterData._id}
              onChange={e => this.onFilterChange(e.target.value, "_id")}
              placeholder="输入用户ID"
            />
          </Col>
          <Col span={4}>
            <Input
              value={filterData.tel}
              onChange={e => this.onFilterChange(e.target.value, "tel")}
              placeholder="输入手机号"
            />
          </Col>
          <Col span={4}>
            <Input
              value={filterData.nickname}
              onChange={e => this.onFilterChange(e.target.value, "nickname")}
              placeholder="输入昵称"
            />
          </Col>
          <Col span={4}>
            <Select
              style={{ width: "100%" }}
              placeholder="选择标签"
              onChange={value => this.onFilterChange(value, "frozenTo")}
              value={filterData.frozenTo}
            >
              <Option value="0">全部</Option>
              <Option value="1">正常账号</Option>
              <Option value="2">冻结账号</Option>
            </Select>
          </Col>
          <Button onClick={() => this.onSearch()}>
            <Icon type="search" />
          </Button>
          <Button onClick={this.resetFilter}>
            <Icon type="close" />
          </Button>
        </Row>
        <Row className="tool-bar">
          <Button
            onClick={() =>
              this.setState({
                showUserModal: true,
                selectUser: {},
                action: "add"
              })}
          >
            <Icon type="plus" />
          </Button>
          {selectedRowKeys.length > 0 && (
            <Button
              type="primary"
              style={{ marginLeft: 8 }}
              onClick={this.removeUser}
            >
              <Icon type="close" />
            </Button>
          )}
        </Row>
        <UserTable
          list={list}
          pagination={pagination}
          selectedRowKeys={selectedRowKeys}
          getUserService={this.getUserService}
          editUser={this.editUser}
          authUser={this.authUser}
          freezUser={this.freezUser}
          onRowSelect={this.onRowSelect}
        />
        {showUserModal && (
          <UserModal
            visible={showUserModal}
            onCancel={this.handleCancel}
            onSearch={this.onSearch}
            user={selectUser}
            action={action}
          />
        )}
        {showFreezModal && <Modal
        title="选择冻结至"
        visible={showFreezModal}
        onOk={this.onFreezSave}
        onCancel={()=>this.setState({showFreezModal: false})}
      >
        <DatePicker
          style={{ width: "100%" }}
          format={dateFormat}
          value={freezDate}
          onChange={(date=>this.setState({freezDate: date}))}
          placeholder="请选择日期"
        />
      </Modal>}
      </div>
    );
  }
}
function mapStateToProps(state) {
  const { user, appData } = state;
  return {
    user,
    users: appData.users,
  };
}
export default connect(mapStateToProps)(UserManage);
